package com.yesjava.springbootjpa.demo.service;

import com.yesjava.springbootjpa.demo.dao.GoodsDao;
import com.yesjava.springbootjpa.demo.entity.Category;
import com.yesjava.springbootjpa.demo.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsService {
    @Autowired
    GoodsDao goodsDao;

    @Autowired
    CategoryService categoryService;

    /**
     * 添加或更改
     * @param goods
     */
    public void saveOrUpdateGoods(Goods goods){
        goodsDao.save(goods);
    }

    /**
     * 查询一个
     * @param id
     * @return
     */
    public Goods findGoodsById(Integer id){
        Goods goods = goodsDao.findById(id).get();
        return goods;
    }


    public Page<Goods> findAllGoods(int pageNo,int pageSize){
        PageRequest pageRequest = PageRequest.of((pageNo - 1) * pageSize, pageSize);
        return  goodsDao.findAll(pageRequest);
    }

    public Page<Goods> findGoodsByCategory(Category category, int pageNo, int pageSize){
        //1. 查询出所有的类别和子类别
        List<Category> allCategory = categoryService.findCategoryAndChildredById(category.getId());
        return  goodsDao.getGoodsByCategoryIn(allCategory,PageRequest.of((pageNo - 1) ,pageSize));
    }

    public void deleteGoods(Goods goods){
        goodsDao.deleteById(goods.getId());
    }

    public void deleteBatchGoods(List<Goods> goodsList){
        goodsDao.deleteInBatch(goodsList);
    }

}
